//
//  RegisterViewController.m
//  EasyToTesco2.0
//
//  Created by 袖手旁觀 on 16/6/20.
//  Copyright © 2016年 EasyToTesco. All rights reserved.
//

#import "RegisterViewController.h"
#import "JudgePhoneNumberBelong.h"

#define Margin 8

#define RegisterViewUIWidth self.view.width - Margin * 4



@interface RegisterViewController ()<UITextFieldDelegate>

/**
 *  用户名
 */
@property (nonatomic,strong)UITextField *nameTextField;

/**
 *  密码
 */
@property (nonatomic,strong)UITextField *setUpPassWordTextField;

/**
 *  再次输入密码
 */
@property (nonatomic,strong)UITextField *certainTextField;

/**
 *  交易密码
 */
@property (nonatomic,strong)UITextField *paySecretCodeTextField;


/**
 邀请码
 */
@property(nonatomic,strong)UITextField *invitationCodeTextField;

@end

@implementation RegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self setUpNavigationBar];
    
    [self loadRegisterViewUI];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)setUpNavigationBar {
    
    self.navigationController.navigationBar.backgroundColor = DEFAULT_COLOR;
    
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem barButtonItemWithImage:[UIImage imageNamed:@"jiantou"] highImage:[UIImage imageNamed:@"jiantou"] target:self action:@selector(backToPre) forControlEvents:UIControlEventTouchUpInside title:nil];
    self.navigationItem.leftBarButtonItem.imageInsets = UIEdgeInsetsMake(0, 0, 0, 0);
    
    
    UILabel *customLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
    [customLab setTextColor:[UIColor whiteColor]];
    customLab.textAlignment = NSTextAlignmentCenter;
    [customLab setText:@"注册"];
    customLab.font = [UIFont boldSystemFontOfSize:15];
    self.navigationItem.titleView = customLab;
    
}

/**
 *  返回按钮点击方法
 */
- (void)backToPre {
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)loadRegisterViewUI {
    
    CGFloat LabelTextFont;
    CGFloat PlaceholderFont;
    
    if (iPhone5) {
        LabelTextFont = 14;
        PlaceholderFont = 14;
    } else {
        LabelTextFont = 15;
        PlaceholderFont = 15;
    }
    
    // 顶部Logo
    UIImageView *logoImageView = [[UIImageView alloc] init];
    logoImageView.image = [UIImage imageNamed:@"icon_logo"];
    [self.view addSubview:logoImageView];
    
    [logoImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.mas_centerX);
        make.top.equalTo(self.view.mas_top).offset(HEIGHT/8);
        make.width.mas_equalTo(WIDTH/5*1.25);
        make.height.mas_equalTo(self.view.width/5);
    }];
    
    // 第一行
    UILabel *nameLabel = [[UILabel alloc] init];
    nameLabel.text = @" 用户名:";
    nameLabel.font = [UIFont systemFontOfSize:LabelTextFont];
    nameLabel.textAlignment = NSTextAlignmentLeft;
    [self.view addSubview:nameLabel];
    
    [nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).with.offset(Margin * 2);
        make.top.equalTo(logoImageView.mas_bottom).with.offset(Margin * 2);
        make.width.mas_equalTo(self.view.width * 0.2);
        make.height.mas_equalTo(25);
    }];
    
    UITextField *nameTextField = [[UITextField alloc] init];
    nameTextField.placeholder = @" 请输入手机号";
    nameTextField.font = [UIFont systemFontOfSize:PlaceholderFont];
    self.nameTextField = nameTextField;
    self.nameTextField.delegate = self;
    [self.view addSubview:nameTextField];
    
    [nameTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(nameLabel.mas_right).with.offset(Margin);
        make.top.equalTo(logoImageView.mas_bottom).with.offset(Margin * 2);
        make.right.equalTo(self.view.mas_right).with.offset(-Margin * 2);
        make.height.mas_equalTo(25);
    }];

    UIView *nameBottomView = [[UIView alloc] init];
    nameBottomView.backgroundColor = [UIColor blackColor];
    nameBottomView.alpha = 0.1;
    [self.view addSubview:nameBottomView];
    
    [nameBottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(nameTextField.mas_bottom).with.offset(5);
        make.centerX.equalTo(self.view.mas_centerX);
        make.width.mas_equalTo(RegisterViewUIWidth);
        make.height.mas_equalTo(1);
    }];
    
    // 第二行
    UILabel *setUpPassWord = [[UILabel alloc] init];
    setUpPassWord.text = @" 设置密码:";
    setUpPassWord.font = [UIFont systemFontOfSize:LabelTextFont];
    setUpPassWord.textAlignment = NSTextAlignmentLeft;
    [self.view addSubview:setUpPassWord];
    
    [setUpPassWord mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).with.offset(Margin * 2);
        make.top.equalTo(nameBottomView.mas_bottom).with.offset(Margin * 2);
        make.width.mas_equalTo(self.view.width * 0.2);
        make.height.mas_equalTo(25);
    }];
    
    UITextField *setUpPassWordTextField = [[UITextField alloc] init];
    setUpPassWordTextField.placeholder = @" 请输入 6-20 位，数字或字母组成";
    setUpPassWordTextField.font = [UIFont systemFontOfSize:PlaceholderFont];
    setUpPassWordTextField.secureTextEntry = YES;
    setUpPassWordTextField.clearButtonMode = UITextFieldViewModeAlways;
    self.setUpPassWordTextField = setUpPassWordTextField;
    self.setUpPassWordTextField.delegate = self;
    [self.view addSubview:setUpPassWordTextField];
    
    [setUpPassWordTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(setUpPassWord.mas_right).with.offset(Margin);
        make.top.equalTo(nameBottomView.mas_bottom).with.offset(Margin * 2);
        make.right.equalTo(self.view.mas_right).with.offset(-Margin * 2);
        make.height.mas_equalTo(25);
    }];
    
    UIView *setUpPassWordBottom = [[UIView alloc] init];
    setUpPassWordBottom.backgroundColor = [UIColor blackColor];
    setUpPassWordBottom.alpha = 0.1;
    [self.view addSubview:setUpPassWordBottom];
    
    [setUpPassWordBottom mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(setUpPassWordTextField.mas_bottom).with.offset(5);
        make.centerX.equalTo(self.view.mas_centerX);
        make.width.mas_equalTo(RegisterViewUIWidth);
        make.height.mas_equalTo(1);
    }];
    
    // 第三行
    UILabel *certainLabel = [[UILabel alloc] init];
    certainLabel.text = @" 确认密码:";
    certainLabel.font = [UIFont systemFontOfSize:LabelTextFont];
    certainLabel.textAlignment = NSTextAlignmentLeft;
    [self.view addSubview:certainLabel];
    
    [certainLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).with.offset(Margin * 2);
        make.top.equalTo(setUpPassWordBottom.mas_bottom).with.offset(Margin * 2);
        make.width.mas_equalTo(self.view.width * 0.2);
        make.height.mas_equalTo(25);
    }];
    
    UITextField *certainTextField = [[UITextField alloc] init];
    certainTextField.placeholder = @" 再次输入，确保输入密码一致";
    certainTextField.font = [UIFont systemFontOfSize:PlaceholderFont];
    certainTextField.secureTextEntry = YES;
    certainTextField.clearButtonMode = UITextFieldViewModeAlways;
    self.certainTextField = certainTextField;
    self.certainTextField.delegate = self;
    [self.view addSubview:certainTextField];
    
    [certainTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(certainLabel.mas_right).with.offset(Margin);
        make.top.equalTo(setUpPassWordBottom.mas_bottom).with.offset(Margin * 2);
        make.right.equalTo(self.view.mas_right).with.offset(-Margin * 2);
        make.height.mas_equalTo(25);
    }];
    
    UIView *certainBottom = [[UIView alloc] init];
    certainBottom.backgroundColor = [UIColor blackColor];
    certainBottom.alpha = 0.1;
    [self.view addSubview:certainBottom];
    
    [certainBottom mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(certainTextField.mas_bottom).with.offset(5);
        make.centerX.equalTo(self.view.mas_centerX);
        make.width.mas_equalTo(RegisterViewUIWidth);
        make.height.mas_equalTo(1);
    }];
    
    // 第四行
    UILabel *paySecretCodeLabel = [[UILabel alloc] init];
    paySecretCodeLabel.text = @" 支付密码:";
    paySecretCodeLabel.font = [UIFont systemFontOfSize:LabelTextFont];
    paySecretCodeLabel.textAlignment = NSTextAlignmentLeft;
    [self.view addSubview:paySecretCodeLabel];
    
    [paySecretCodeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).with.offset(Margin * 2);
        make.top.equalTo(certainBottom.mas_bottom).with.offset(Margin * 2);
        make.width.mas_equalTo(self.view.width * 0.2);
        make.height.mas_equalTo(25);
    }];
    
    
    UITextField *paySecretCodeTextField = [[UITextField alloc] init];
    paySecretCodeTextField.placeholder = @" 请输入支付密码";
    paySecretCodeTextField.font = [UIFont systemFontOfSize:PlaceholderFont];
    paySecretCodeTextField.secureTextEntry = YES;
    paySecretCodeTextField.clearButtonMode = UITextFieldViewModeAlways;
    self.paySecretCodeTextField = paySecretCodeTextField;
    self.paySecretCodeTextField.delegate = self;
    self.paySecretCodeTextField.tag = 101;
    [self.view addSubview:paySecretCodeTextField];
    
    
    [paySecretCodeTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(certainLabel.mas_right).with.offset(Margin);
        make.top.equalTo(certainBottom.mas_bottom).with.offset(Margin * 2);
        make.right.equalTo(self.view.mas_right).with.offset(-Margin * 2);
        make.height.mas_equalTo(25);
    }];
    
    UIView *paySecretCodeBottom = [[UIView alloc] init];
    paySecretCodeBottom.backgroundColor = [UIColor blackColor];
    paySecretCodeBottom.alpha = 0.1;
    [self.view addSubview:paySecretCodeBottom];
    
    [paySecretCodeBottom mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(paySecretCodeTextField.mas_bottom).with.offset(5);
        make.centerX.equalTo(self.view.mas_centerX);
        make.width.mas_equalTo(RegisterViewUIWidth);
        make.height.mas_equalTo(1);
    }];
    
    // 第w5行
    UILabel *invitationCodeLabel = [[UILabel alloc] init];
    invitationCodeLabel.text = @" 邀请码:";
    invitationCodeLabel.font = [UIFont systemFontOfSize:LabelTextFont];
    invitationCodeLabel.textAlignment = NSTextAlignmentLeft;
    [self.view addSubview:invitationCodeLabel];
    
    [invitationCodeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).with.offset(Margin * 2);
        make.top.equalTo(paySecretCodeBottom.mas_bottom).with.offset(Margin * 2);
        make.width.mas_equalTo(self.view.width * 0.2);
        make.height.mas_equalTo(25);
    }];
    
    invitationCodeLabel.hidden = true;
    
    UITextField *invitationCodeTextField = [[UITextField alloc] init];
    invitationCodeTextField.placeholder = @" 请输入邀请码";
    invitationCodeTextField.font = [UIFont systemFontOfSize:PlaceholderFont];
    invitationCodeTextField.clearButtonMode = UITextFieldViewModeAlways;
    self.invitationCodeTextField = invitationCodeTextField;
    self.invitationCodeTextField.delegate = self;
    self.invitationCodeTextField.tag = 102;
    [self.view addSubview:invitationCodeTextField];
    [self.invitationCodeTextField addTarget:self action:@selector(invitationCodeTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    
    invitationCodeTextField.hidden = true;
    
    [invitationCodeTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(paySecretCodeLabel.mas_right).with.offset(Margin);
        make.top.equalTo(paySecretCodeBottom.mas_bottom).with.offset(Margin * 2);
        make.right.equalTo(self.view.mas_right).with.offset(-Margin * 2);
        make.height.mas_equalTo(25);
    }];
    
    UIView *invitationCodeBottom = [[UIView alloc] init];
    invitationCodeBottom.backgroundColor = [UIColor blackColor];
    invitationCodeBottom.alpha = 0.1;
    [self.view addSubview:invitationCodeBottom];
    
    invitationCodeBottom.hidden = true;
    
    [invitationCodeBottom mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(invitationCodeTextField.mas_bottom).with.offset(5);
        make.centerX.equalTo(self.view.mas_centerX);
        make.width.mas_equalTo(RegisterViewUIWidth);
        make.height.mas_equalTo(1);
    }];
    
    // 注册按钮
    UIButton *RegisterButton = [[UIButton alloc] init];
    [RegisterButton setTitle:@"注册" forState:UIControlStateNormal];
    [RegisterButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    RegisterButton.backgroundColor = DEFAULT_COLOR;
    RegisterButton.layer.cornerRadius = 3;
    RegisterButton.layer.masksToBounds = YES;
    [RegisterButton addTarget:self action:@selector(didClickRegisterButton) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:RegisterButton];
    
    [RegisterButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.mas_centerX);
        make.top.equalTo(invitationCodeBottom.mas_bottom).with.offset(HEIGHT/16);
        make.width.mas_equalTo(RegisterViewUIWidth);
        make.height.mas_equalTo(40);
    }];
    
    CGFloat BackLogInFont;
    CGFloat BackLogInWidth;
    
    if (iPhone5) {
        BackLogInFont = 12;
        BackLogInWidth =  self.view.width/3 + Margin * 2;
    } else {
        BackLogInFont = 13;
        BackLogInWidth = self.view.width/3 ;
    }
    
    // 返回登录按钮
    UIButton *BackLogIn = [[UIButton alloc] init];
    [BackLogIn setTitle:@"已有账号，现在登录" forState:UIControlStateNormal];
    [BackLogIn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    BackLogIn.titleLabel.textAlignment = NSTextAlignmentRight;
    BackLogIn.titleLabel.font = [UIFont systemFontOfSize:BackLogInFont];
    [BackLogIn addTarget:self action:@selector(didClickBackLogInButton) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:BackLogIn];
    
    [BackLogIn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view.mas_right).with.offset(-Margin * 2);
        make.top.equalTo(RegisterButton.mas_bottom).with.offset(Margin);
        make.width.mas_equalTo(BackLogInWidth);
        make.height.mas_equalTo(25);
    }];
}

/**
 *  注册按钮
 */
- (void)didClickRegisterButton {
    [self registerAllTextField];
    
    BOOL isNumber = [self isPureNumandCharacters:self.invitationCodeTextField.text];
    if (isNumber) {
        NSLog(@"数字");
    }else{
        NSLog(@"不符")
    }
    
    
    NSLog(@"注册");
    if (self.nameTextField.text.length != 0 && self.setUpPassWordTextField.text.length != 0 && self.certainTextField.text.length != 0 && self.paySecretCodeTextField.text.length != 0) {
        BOOL judge = [JudgePhoneNumberBelong isMobileNumber:self.nameTextField.text];
        if (judge == YES) {
            if (![self.setUpPassWordTextField.text isEqualToString:self.certainTextField.text]) {
                
                MBProgressHUD *hud = [MBProgressHUD showMessage:@"两次输入密码不一致.请重新输入" toView:self.view dimBackground:NO AndCompleteBlock:^(id object) {
                    self.setUpPassWordTextField.text = nil;
                    self.certainTextField.text = nil;
                }];
                
                [self.view addSubview:hud];
                
            } else {
                [self requestregisterDatasourse];
            }
        } else {
            MBProgressHUD *hud = [MBProgressHUD showMessage:@"手机号码格式有误, 请重新输入" toView:self.view dimBackground:NO AndCompleteBlock:nil];
            
            [self.view addSubview:hud];
        }
        
    } else {
        MBProgressHUD *hud = [MBProgressHUD showMessage:@"请完善您的注册信息" toView:self.view dimBackground:NO AndCompleteBlock:nil];
        
        [self.view addSubview:hud];
    }

}


/**
 *  手机号码输入设置
 */
- (void)invitationCodeTextFieldDidChange:(UITextField *)textField
{
    
    if (textField.tag == 102) {
        if (textField.text.length >=8) {
            textField.text = [textField.text substringToIndex:8];
        }
    }
}


- (BOOL)isPureNumandCharacters:(NSString *)string

{
    string = [string stringByTrimmingCharactersInSet:[NSCharacterSet decimalDigitCharacterSet]];
    if(string.length > 0)
    {
        return NO;
    }
    return YES;
    
}



/**
 *  返回登录按钮
 */
- (void)didClickBackLogInButton {
    [self backToPre];
}

//开始编辑输入框的时候，软键盘出现，执行此事件
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    if (textField.tag == 101|| textField.tag == 102) {
        CGRect frame = textField.frame;
        int offset = frame.origin.y + 80 - (self.view.frame.size.height - 216.0);//键盘高度216
        
        //将视图的Y坐标向上移动offset个单位，以使下面腾出地方用于软键盘的显示
        if(offset > 0)
            self.view.frame = CGRectMake(0.0f, -offset, self.view.frame.size.width, self.view.frame.size.height);
        
        [UIView commitAnimations];
        
    }
    
    
}

//输入框编辑完成以后，将视图恢复到原始状态
-(void)textFieldDidEndEditing:(UITextField *)textField
{
    self.view.frame =CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    //    NSLog(@"%@", textField.text);
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self registerAllTextField];
}

- (void)registerAllTextField {
    [self.nameTextField resignFirstResponder];
    [self.paySecretCodeTextField resignFirstResponder];
    [self.setUpPassWordTextField resignFirstResponder];
    [self.certainTextField resignFirstResponder];
    [self.invitationCodeTextField resignFirstResponder];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    if (textField == self.paySecretCodeTextField) {
        [self.invitationCodeTextField becomeFirstResponder];
    }
    
    if (textField == self.certainTextField) {
        [self.paySecretCodeTextField becomeFirstResponder];
    }
    
    if (textField == self.nameTextField) {
        [self.setUpPassWordTextField becomeFirstResponder];
    }
    
    if (textField == self.setUpPassWordTextField) {
        [self.certainTextField becomeFirstResponder];
    }
    
    if (textField == self.invitationCodeTextField) {
        [self didClickRegisterButton];
    }
    
    return YES;
}

/**
 *  数据请求
 */
- (void)requestregisterDatasourse {
    
    NSDictionary *params = @{
                             @"username":self.nameTextField.text,
                             @"password":self.certainTextField.text,
                             @"userpwtwo":self.paySecretCodeTextField.text,
                             @"extends_sn":self.invitationCodeTextField.text
                             };
    
    [[NetWorkSharedTools sharedNetWorkTools] objectWithURLDict:params AndMenthodName:@"/api/User/register" completeBlock:^(id object) {
        
        if (JudgeBackDataCode) {
            
            NSLog(@"%@",object);
            MBProgressHUD *hud = [MBProgressHUD showMessage:@"注册成功" toView:self.view dimBackground:false AndCompleteBlock:^(id object) {
                [self backToPre];
            }];
            [self.view addSubview:hud];
            
        }else{
            
            NSDictionary *dict = [object objectForKey:@"message"];
            MBProgressHUD *hud = [MBProgressHUD showMessage:[NSString stringWithFormat:@"%@",dict[@"view"]] toView:self.view dimBackground:NO AndCompleteBlock:nil];
            [self.view addSubview:hud];
            
        }

    }];
}

@end
